package com.yuntoyun.fwcore.base;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.google.gson.JsonObject;
import com.yuntoyun.fwcore.appext.data.FwAppData;
import com.yuntoyun.fwcore.config.FwCodeConfig;
import com.yuntoyun.fwcore.model.FwResultBaseDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.plug.network.retrofit.FwRxApiManager;
import com.yuntoyun.fwcore.util.FwBarUtil;
import com.yuntoyun.fwcore.util.FwDialogUtil;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwMajorizationUtil;
import com.yuntoyun.fwcore.util.FwRxPermissionUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.observers.DisposableObserver;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnMultiCompressListener;

/**
 * 应用 Activity 基础类
 */
public abstract class FwBaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected List<DisposableObserver> fwObserverList = new ArrayList<>();
    protected LayoutInflater fwLayoutInflater;
    protected Bundle fwBundle;
    protected Activity fwActivity;
    protected FwGsonUtil fwGsonUtil;
    protected FwRxPermissionUtil fwRxPermissionUtil;

    private List<String> fwFilePath = new ArrayList<>();

    protected Handler fwHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null == msg.obj)
                return;

            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            //+++++过滤错误提示 起始
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            if (msg.obj instanceof FwResultJsonDataModel) {
                FwResultJsonDataModel model = (FwResultJsonDataModel) msg.obj;
                if (null == model) {
                    return;
                }

                if (FwCodeConfig.CODE_LOGIN_AGAIN == model.getFwStatus()) {
                    FwAppData.clearLoginData();
//                    FwIntentUtil.builder().startActivity(fwActivity, LoginActivity.class, null,
//                            new int[]{
//                                    Intent.FLAG_ACTIVITY_CLEAR_TOP
//                            });
//                    //发送广播
//                    Intent intent = new Intent();
//                    intent.setAction(MainActivity.ACTION_APP_EXIT);
//                    fwActivity.sendBroadcast(intent, MainActivity.PERMISSION_APP_EXIT);
                    FwToastUtil.builder().makeText("账号已在其他设备登录，请重新登录！");
                    return;
                }

                if (FwCodeConfig.CODE_SUCCESSED != model.getFwStatus() && isShowFailedTip()) {
//                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "提示", model
//                            .getFwMessage());
                    FwToastUtil.builder().makeText(model.getFwMessage());
                    return;
                }
                model.setIndex(msg.what);
                messageHandler(model);
            } else if (msg.obj instanceof FwResultJsonListDataModel) {
                FwResultJsonListDataModel model = (FwResultJsonListDataModel) msg.obj;
                if (null == model) {
                    return;
                }
                if (FwCodeConfig.CODE_LOGIN_AGAIN == model.getFwStatus()) {
                    FwAppData.clearLoginData();
//                    FwIntentUtil.builder().startActivity(fwActivity, LoginActivity.class, null,
//                            new int[]{
//                                    Intent.FLAG_ACTIVITY_CLEAR_TOP
//                            });
//                    //发送广播
//                    Intent intent = new Intent();
//                    intent.setAction(MainActivity.ACTION_APP_EXIT);
//                    fwActivity.sendBroadcast(intent, MainActivity.PERMISSION_APP_EXIT);
                    FwToastUtil.builder().makeText("账号已在其他设备登录，请重新登录！");
                    return;
                }
                if (FwCodeConfig.CODE_SUCCESSED != model.getFwStatus() && isShowFailedTip()) {
//                    FwAlertDialogUtil.builder().showCustomDialog(fwActivity, "提示", model
//                            .getFwMessage());
                    FwToastUtil.builder().makeText(model.getFwMessage());
                    return;
                }
                model.setIndex(msg.what);
                messageHandler(model);
            } else {
                messageHandler(msg);
            }
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            //+++++过滤错误提示 结束
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initCreate();
        setContentView(getLayoutResId());
        fwActivity = this;
        fwBundle = getIntent().getExtras();
        //工具类
        fwRxPermissionUtil = new FwRxPermissionUtil(this);
        fwGsonUtil = FwGsonUtil.builder();
        //加载插件
        ButterKnife.bind(this);
        fwLayoutInflater = LayoutInflater.from(this);
        //抽象方法
        initNavigation();
        initView();
        initEvent();
        initData();
    }

    protected void doPostData(int what, Observable<FwResultJsonDataModel> observable, boolean
            showloading) {
        FwOkHttp.instance().doPost(this, fwHandler.obtainMessage(what), observable, fwObserverList,
                showloading);
    }

    protected void doPostListData(int what, Observable<FwResultJsonListDataModel> observable,
                                  boolean showloading) {
        FwOkHttp.instance().doPost(this, fwHandler.obtainMessage(what), observable, fwObserverList,
                showloading);
    }

    protected void doPostBaseData(int what, Observable<FwResultBaseDataModel<JsonObject>>
            observable, boolean
                                          showloading) {
        FwOkHttp.instance().doPost(this, fwHandler.obtainMessage(what), observable, fwObserverList,
                showloading);
    }

    /**
     * 发送请求 (带图片)
     *
     * @param compressCallback
     */
    protected void doPostImageData(ICompressCallback compressCallback) {

        final List<File> files = new ArrayList<>();
        for (int i = 0; i < fwFilePath.size(); i++) {
            String path = fwFilePath.get(i);
            if (!TextUtils.isEmpty(path.trim())) {
                File file = new File(path);
                files.add(file);
            }
        }

        if (files.size() > 0) {
            Luban.compress(this, files)//传入组图文件数组
                    .setMaxSize(120)
                    .putGear(Luban.CUSTOM_GEAR)//压缩模式
                    .launch(new OnMultiCompressListener() {
                        @Override
                        public void onStart() {
                            FwDialogUtil.showLoading(fwActivity, "", true);
                        }

                        @Override
                        public void onSuccess(List<File> fileList) {
                            // （压缩后的），建议全局化file，像listpath一样；
                            FwDialogUtil.dismissLoading();
                            compressCallback.callback(fileList);
                        }

                        @Override
                        public void onError(Throwable e) {
                            FwDialogUtil.dismissLoading();
                            FwToastUtil.builder().makeText("提交失败");
                        }
                    });
        } else {
            compressCallback.callback(null);
        }
    }

    protected abstract void beforeLayout();

    protected abstract int getLayoutResId();

    protected abstract void initView();

    protected abstract void initData();

    protected abstract void initEvent();

    protected abstract void initNavigation();

    protected abstract void messageHandler(Message msg);

    protected abstract void messageHandler(FwResultJsonDataModel model);

    protected abstract void messageHandler(FwResultJsonListDataModel model);

    @Override
    protected void onDestroy() {
        FwRxApiManager.init().cancelAll(fwObserverList);
        super.onDestroy();
    }

    //========================================================================

    public void setFwFilePath(String filePath, boolean isClear) {
        if (isClear) fwFilePath.clear();

        if (!TextUtils.isEmpty(filePath))
            this.fwFilePath.add(filePath);
    }

    public void setFwFilePath(List<String> filePathList, boolean isClear) {
        if (isClear) fwFilePath.clear();

        this.fwFilePath.addAll(filePathList);
    }


    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //压缩回调接口
    protected interface ICompressCallback {
        void callback(List<File> fileList);
    }

    protected boolean isShowFailedTip() {
        return true;
    }

    /**
     * @param fullScreen
     * @param screenOrientation
     */
    protected void initScreenDefault(boolean fullScreen, int screenOrientation) {
//        if (fullScreen) {
//            setTheme(android.R.style.Theme_Light_NoTitleBar_Fullscreen);
//        }
//        if (-1 != screenOrientation) {
//            setRequestedOrientation(screenOrientation);
//        }
    }

    /**
     * 检测快速点击
     *
     * @return
     */
    protected boolean isFastClick() {
        boolean isFast = FwMajorizationUtil.builder().isFastClick();
        if (isFast) {
            FwToastUtil.builder().makeText("禁止快速重复点击！");
        }
        return isFast;
    }

    /**
     * Layout之前运行
     */
    private void initCreate() {
//        initScreenDefault(false, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initStatusBar();
        beforeLayout();
    }

    //++++++++++++++++++++++++++++++++++++++++++
    //系统设置
    //++++++++++++++++++++++++++++++++++++++++++

    //状态栏样式
    private void initStatusBar() {
        //浅色背景需要高亮显示
        FwBarUtil.setStatusBarLightMode(this, true);
    }

    //隐藏底部导航栏
    private void setHideBottomBar() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }
}
